package com.ledict.casefiling.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import javax.sql.DataSource;
import javax.xml.crypto.Data;
import java.io.IOException;

@Configuration
public class MyBatisConfig {
    @Autowired
    private DataSource dataSource;

    @Bean(name = "sqlSessionFactory")
    public SqlSessionFactoryBean sqlSessionFactory() {
        System.out.println("================= sqlSqssionFactoryBean ===============");

        SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        try {
            Resource[] mapperXmlResources = resolver.getResources("classpath:mapper/*.xml");
            Resource configResource = resolver.getResource("classpath:config/mybatis-config.xml");
            sqlSessionFactory.setDataSource(dataSource);
            sqlSessionFactory.setMapperLocations(mapperXmlResources);
            sqlSessionFactory.setConfigLocation(configResource);
            sqlSessionFactory.setTypeAliasesPackage("com.ledict.casefiling.entity");
        } catch (IOException e) {
            e.printStackTrace();
        }

        return sqlSessionFactory;
    }

    @Bean
    public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

/*    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer() {
        MapperScannerConfigurer configurer = new MapperScannerConfigurer();
        configurer.setBasePackage("com.ledict.casefiling.dao");
        configurer.setSqlSessionFactoryBeanName("sqlSessionFactory");

        return configurer;
    }*/
}
